package gecko.x;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 陈永佳 (yoojiachen@gmail.com)
 * @since 1.0.0
 */
public class MergeX {

    @SuppressWarnings("unchecked")
    public static Map<String, Object> merge(Map<String, Object> base, Map<String, Object> replacement) {
        final Map<String, Object> target = new HashMap<>(base);
        replacement.forEach((key, newValue) -> {
            if (target.containsKey(key)) {
                // 两个数值，类型相同则合并：
                // 1. List: 合并
                // 2. Map: 再merge
                // 如果类型不同，则Source替换Target
                final Object existsValue = target.get(key);
                if (existsValue instanceof List) {
                    if (newValue instanceof List) {
                        ((List) existsValue).addAll(((List) newValue));
                    } else {
                        target.put(key, newValue);
                    }
                } else if (existsValue instanceof Map) {
                    if (newValue instanceof Map) {
                        target.put(key, merge(((Map) existsValue), ((Map) newValue)));
                    } else {
                        target.put(key, newValue);
                    }
                } else {
                    target.put(key, newValue);
                }

            } else {
                target.put(key, newValue);
            }

        });

        return target;
    }
}
